# -*- coding: utf-8 -*-


from django.db import models
from django.contrib.auth.models import User


# Create your models here.

class Post(models.Model):
    name = models.CharField(max_length = 64, verbose_name = "Название",core = True)
    description = models.TextField(verbose_name = "Описание");

    def __unicode__(self):
        return u'%s' % (self.name)
    class Admin:
        ordering = ('name',)
    class Meta:
        verbose_name = "Должность"
        verbose_name_plural = "Должности"
    
class Manager(models.Model):
    firstName = models.CharField(max_length = 64, verbose_name = "Имя")
    secondName = models.CharField(max_length = 64, verbose_name = "Отчество")
    lastName = models.CharField(max_length = 64, verbose_name = "Фамилия")
    postName = models.ForeignKey(Post, verbose_name ="Должность")
    user = models.ForeignKey(User, unique=True)
    
    def __unicode__(self):
        return u'%s %s %s' % (self.firstName, self.secondName, self.lastName)
    class Admin:
        ordering = ('firstName',)
    class Meta:
        verbose_name = "Менеджер"
        verbose_name_plural = "Менеджеры"
    
class Client (models.Model):
    orgName = models.CharField(max_length = 128, verbose_name = 'Заказчик')
    address1 = models.CharField(max_length = 128, verbose_name = 'Адрес',
                                null = True, blank = True)
    address2 = models.CharField(max_length = 128, verbose_name = 'Адрес 2',
                                null = True, blank = True)
    phone1 =  models.CharField(max_length = 128, verbose_name = "Телефон 1")
    phone2 =  models.CharField(max_length = 128, verbose_name = "Телефон 2",
                                null = True, blank = True)
    fax =  models.CharField(max_length = 128, verbose_name = "Факс",
                                null = True, blank = True)
    email = models.EmailField( verbose_name = "Электронная почта",
                                null = True, blank = True)
    info = models.TextField( verbose_name = "Комментарий",
                                null = True, blank = True)
    inn = models.CharField(max_length = 128, verbose_name = 'ИНН',
                                null = True, blank = True)
    kpp = models.CharField(max_length = 128, verbose_name = 'КПП',
                                null = True, blank = True)
    bik = models.CharField(max_length = 128, verbose_name = 'БИК',
                                null = True, blank = True)
    cor_accaunt = models.CharField(max_length = 128, verbose_name = 'Кор счет',
                                null = True, blank = True)
    ras_account = models.CharField(max_length = 128, verbose_name = 'Расчетный счет',
                                null = True, blank = True)
    bank = models.CharField(max_length = 128, verbose_name = 'Банк',
                                null = True, blank = True)
    image = models.ImageField(upload_to = 'client_images',
                                verbose_name = "Схема проезда" , null = True, blank = True)
    www = models.TextField(verbose_name = "сайт",
                                null = True, blank = True)
    
    def __unicode__(self):
        return u'%s' % (self.orgName)
    class Admin:
         search_fields = ['orgName', 'email', 'phone1']
         ordering = ('orgName',)
    class Meta:
        verbose_name = "Клиент"
        verbose_name_plural = "Клиенты"
       
    
class Parthner(models.Model):
    firstName = models.CharField(max_length = 64, verbose_name = "Имя")
    secondName = models.CharField(max_length = 64, verbose_name = "Отчество")
    lastName = models.CharField(max_length = 64, verbose_name = "Фамилия")
    birthDate = models.DateField( verbose_name = "День рождения",
                                  null = True, blank = True)
    phone = models.CharField(max_length = 128, verbose_name = "Телефон")
    mobilePhone = models.CharField(max_length = 128, verbose_name = "Мобильный телефон",
                                   null = True, blank = True) 
    fax = models.CharField(max_length = 128, verbose_name = "Факс",
                           null = True, blank = True )
    email = models.EmailField(verbose_name = "Электронная почта")
    www = models.TextField(verbose_name = "Сайт",
                           null = True, blank = True)
    client = models.ManyToManyField(Client, verbose_name = "Клиент", null = True, blank = True);
    def __unicode__(self):
        return u'%s %s %s' % (self.firstName, self.secondName, self.lastName)
    class Admin:
        ordering = ('firstName',)
    class Meta: 
        verbose_name = "Персона"
        verbose_name_plural = "Персоны"
    
class Workshop(models.Model):
    name = models.CharField(max_length = 64, verbose_name = "Название")
    description = models.TextField( verbose_name = "Описание")
    
    def __unicode__(self):
        return u'%s' % (self.name)
       
    class Admin:
        ordering = ('name',)
    class Meta:
        verbose_name = "Цех"
        verbose_name_plural = "Цеха"

class Category(models.Model):
    name = models.CharField(max_length = 64, verbose_name = "Название")
    workshop = models.ForeignKey(Workshop, verbose_name = "Цех")
    
    def __unicode__(self):
        return u'%s' % (self.name)
    class Admin:
        ordering = ('name',)
    class Meta:
        verbose_name = "Категория"
        verbose_name_plural = "Категории"

class Unit(models.Model):
    name = models.TextField(max_length = 64, verbose_name = "Название")
    
    def __unicode__(self):
        return u'%s' % (self.name)
    class Meta:
        verbose_name = "Единица измерения"
        verbose_name_plural = "Единицы измерения"
    class Admin:
        ordering = ('name',)

class Color(models.Model):
    color = models.TextField(max_length = 64, verbose_name = "Цвет")
    def __unicode__(self):
       return u'%s' % (self.color)
    class Meta:
       verbose_name = "Цвет"
       verbose_name_plural = "Цвета"
    class Admin:
        ordering = ('color',)
        pass

class Item(models.Model):
    name = models.TextField(max_length = 128, verbose_name = "Название")
    code = models.TextField(max_length = 128, verbose_name = "Код", null = True, blank = True)
    categoryName = models.ForeignKey(Category, verbose_name ="Категория")
    workshop = models.ForeignKey(Workshop, verbose_name = "Цех")
    price1 = models.DecimalField(decimal_places = 2, max_digits = 10,
                                 verbose_name ="Цена 1")
    price2 = models.DecimalField(decimal_places = 2, max_digits = 10,
                                 verbose_name ="Цена 2", null = True, blank = True)
    price3 = models.DecimalField(decimal_places = 2, max_digits = 10,
                                 verbose_name ="Цена 3", null = True, blank = True)
    price4 = models.DecimalField(decimal_places = 2, max_digits = 10,
                                 verbose_name ="Цена 4", null = True, blank = True)
    width = models.DecimalField(decimal_places = 3, max_digits = 10,
                                 verbose_name ="Ширина (м)", null = True, blank = True)
    thick = models.DecimalField(decimal_places = 3, max_digits = 10,
                                 verbose_name ="Толщина (м)", null = True, blank = True)
    unitName = models.ForeignKey(Unit, verbose_name = "Ед. измерения")
    image = models.ImageField(upload_to = 'client_images', verbose_name = "Изображение",
                              null = True, blank = True)
    showimage = models.BooleanField(default = False)
    class Meta: 
        verbose_name = "Товар"
        verbose_name_plural = "Товары"
    def __unicode__(self):
        return u'%s' %  self.name
    class Admin:
        search_fields = ['name',]
        list_filter = ['categoryName', 'workshop']
        ordering = ('name',)


class OrderItem(models.Model):
    item =  models.ForeignKey(Item, null = True, blank = True, verbose_name = 'Товар', raw_id_admin=True)
    order = models.ForeignKey('Order', edit_inline=models.TABULAR, verbose_name = "Заказ")
    price = models.DecimalField(decimal_places = 3, max_digits = 10, core = True, verbose_name = "Цена")
    quantity = models.IntegerField(core = True, verbose_name = "Количество")
    #width = models.DecimalField(decimal_places = 3,
    #                            max_digits = 10,verbose_name = "Ширина (мм)" , null = True, blank = True
    #                            ,visible = False)
    height = models.IntegerField( verbose_name = "Длина (мм)", null = True, blank = True)
    thick = models.IntegerField(verbose_name = "Толщина (мм)", null = True, blank = True)
    pogonag = models.IntegerField(verbose_name = "Погонаж (мм)", null = True, blank = True)
    color  = models.ForeignKey('Color', verbose_name = 'Цвет', null = True, blank = True)
    
    code = models.CharField(max_length = 128, verbose_name = "Код", null = True, blank = True)
    
    def save(self):
      self.pogonag = (abs(self.height-50)/350+1)*18+self.height
      models.Model.save(self)  
    
    class Meta: 
        verbose_name = "Позиция"
        verbose_name_plural = "Позиции" 
    
class Order(models.Model):
    invoice = models.ForeignKey('Invoice', verbose_name = "Счет",
                                null = True, blank = True,)
    dateCreate  = models.DateTimeField(auto_now_add = True, core = True,
                                       editable = False, verbose_name = "Дата создания")
    dateUpdate  = models.DateTimeField(auto_now = True, core = False,
                                       editable = False, verbose_name = "Дата обновления")
    workshop = models.ForeignKey('Workshop', verbose_name = "Цех", null = True, blank = True,)
    status = models.IntegerField( choices=((0,"Новый"), (1, "В процессе" ) , (2, "Готов" ),(3, "Скрыт")),
                                  default = 0,
                                  verbose_name = "Статус")
    manager = models.ForeignKey(Manager, verbose_name = "Менеджер")
    comment = models.TextField(verbose_name = "Примечание",
                           null = True, blank = True)
    
    def client(self):
        return  self.invoice.client     
   
    def addInvoiceItem(self, item):
        oi = OrderItem()
        oi.item = item.item
        oi.price = item.price
        oi.quantity = item.quantity
        oi.height = item.height*1000
        oi.height = item.heigh*1000
        oi.color = item.color
        oi.thick  = item.thick*1000
        oi.order = self
        oi.code = item.code
        oi.pogonag = (abs(oi.width-50)/350+1)*18+oi.width
        oi.save()
    
    def getUrl(self):
        return '<a href="blblbbla">aaaa</a>'
     
    def __unicode__(self):
        return u"Заказ #%s" % (self.id)
    
    class Admin:
        fields = (
        (None, {'fields': ('invoice', 'manager', 'dateCreate','dateUpdate','status', 'workshop', 'comment')}),
        )
        list_display = ('id', 'dateCreate', 'dateUpdate', 'invoice', 'workshop', 'status')
        list_filter = ['dateCreate', 'dateUpdate', 'status', 'workshop']
        search_fields = ['dateCreate', 'client', 'status', 'workshop']
        
        
    class Meta: 
        verbose_name = "Заказ"
        verbose_name_plural = "Заказы"

class InvoiceItem(models.Model):
    item =  models.ForeignKey(Item, null = True, blank = True, verbose_name = "Товар", raw_id_admin=True)
   
    invoice = models.ForeignKey('Invoice', edit_inline=models.TABULAR, num_in_admin = 10,
                                min_num_in_admin = 1, num_extra_on_change = 1,
                                raw_id_admin=True)
    price = models.DecimalField(decimal_places = 2, max_digits = 10, core = True, verbose_name = "Цена единицы")
    quantity = models.IntegerField(core = True, verbose_name = "Количество")
    width = models.DecimalField(decimal_places = 3,
                                max_digits = 10,verbose_name = "Ширина (м)" , null = True, blank = True)
    height = models.DecimalField(decimal_places = 3,
                                max_digits = 10,verbose_name = "Длина (м)", null = True, blank = True)
    color = models.ForeignKey('Color', verbose_name = 'Цвет', null = True, blank = True)

    itemarea = models.DecimalField(decimal_places = 3,
                                max_digits = 10,verbose_name = "Площадь листа (кв. м)", null = True, blank = True)
 
    areaprice = models.DecimalField(decimal_places = 2,
                                max_digits = 10,
                                null = True,
                                blank = True,
                               # editable = False,
                                verbose_name = "Цена листа")
    
    totalarea = models.DecimalField(decimal_places = 3,
                                    max_digits = 10,
                                    verbose_name = "Общая площадь (кв. м)", null = True, blank = True)
    
    total = models.DecimalField(decimal_places = 2,
                                max_digits = 10,
                                null = True,
                                blank = True,
                               # editable = False,
                                verbose_name = "Всего")

    def save(self):
        if self.price and self.quantity and self.width and self.height:
            self.total = self.price * self.quantity * self.width * self.height                
        super(InvoiceItem, self).save()
        
        invoice = self.invoice
        invoice.sum = 0
        items = invoice.invoiceitem_set.all()
        for item in items:
            invoice.sum += item.total;
        print invoice.sum
        invoice.save()
       
        
    class Meta: 
        verbose_name = "Позиция"
        verbose_name_plural = "Позиции"
            
    def __unicode__(self):
        return u'%s' % (self.item.name)
    
class Invoice(models.Model):
    client = models.ForeignKey( Client, verbose_name="Клиент", raw_id_admin=True)
    dateCreate  = models.DateTimeField(auto_now_add = True, core = True,
                                       editable = False, verbose_name="Дата создания")
    dateUpdate  = models.DateTimeField(auto_now = True, core = True,
                                       editable = False, verbose_name="Дата обновления")
    status = models.IntegerField( 
                    choices=((0,"Новый"), (1, "В процессе" ) , (2, "Готов" ),(3, "Скрыт")),
                    default = 0,
                    verbose_name = "Статус")
    
    sum  =  models.DecimalField(decimal_places = 2,
                                max_digits = 10,
                                null = True,
                                blank = True,
                                #editable = False,
                                verbose_name = "Всего")
    
    manager = models.ForeignKey(Manager, verbose_name = "Менеджер")
    
    comment = models.TextField(verbose_name = "Примечание",
                           null = True, blank = True)
    
    exploded  = models.IntegerField(default = 0, blank = True, editable = False)
        
    def isExploded(self):
	   if self.exploded == 1: return True
	   return False  
        
    def generateOrders(self):
        orderlist = {}
        self.exploded = 1
        self.save()
        for item in self.invoiceitem_set.all():
            if not orderlist.has_key(item.item.workshop.id):
                orderlist[item.item.workshop.id] = Order()
                orderlist[item.item.workshop.id].workshop = item.item.workshop
                orderlist[item.item.workshop.id].invoice = self
		orderlist[item.item.workshop.id].manager = self.manager
                orderlist[item.item.workshop.id].save()
            orderlist[item.item.workshop.id].addInvoiceItem(item)          
        return orderlist
    def getOrders(self):
        return self.order_set.all()
    def __unicode__(self):
        return u'Счет #%s' % (self.id)
    class Meta: 
        verbose_name = "Счет"
        verbose_name_plural = "Счета"
    class Admin:
        fields = (
                  (None, {'fields': ('manager','client','status','sum', 'comment')}),
                  (None, {'fields': ('dateCreate','dateUpdate')}),
                  
                  )
        list_display = ('id', 'dateCreate', 'dateUpdate', 'client', 'sum', 'status')
        list_filter = ['dateCreate', 'dateUpdate', 'status', 'client']
        search_fields = ['dateCreate', 'client', 'status']   

       
